//
//  InviteFriendsViewController.m
//  SP2P
//
//  Created by 吴建东 on 16/5/31.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "InviteFriendsViewController.h"
#import "InfoShareView.h"
#import "QRCodeViewController.h"
#import "InviteRuleViewController.h"
#import "CacheUtil.h"
#import "CommonWebViewController.h"

@interface InviteFriendsViewController ()<InfoShareViewDelegate,HTTPClientDelegate>
{
    UIImageView *_publicImageView;
    UILabel *_profitLabel;
    UILabel *_oneLevelNumLabel;
    UILabel *_twoLevelNumLabel;
    ClickButton *_inviteButton;
    
    InfoShareView *_shareView;
    
    NSString *_promoteImg;
    NSString *_spreadLink;
}
@property (nonatomic, strong) UIScrollView  *scrollView;
@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, copy  ) NSString      *cacheFileName;
@end

@implementation InviteFriendsViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_requestClient != nil) {
        [_requestClient cancel];
    }
    if (_shareView) {
        [_shareView cancel];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tabBarController.tabBar setHidden:NO];
    [self requestData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initNavBarTitle:NSLocalizedString(@"Tab_Invite", nil) andLeftItemName:@"" andRightItemName:@"规则"];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self initView];
}

- (void)rightBarButtonClick {
    CommonWebViewController *rule = [[CommonWebViewController alloc] init];
    rule.hidesBottomBarWhenPushed = YES;
    rule.naviTitle = @"邀请好友规则";
    rule.typeStr = @"InviteRule";
    rule.requestUrl = [NSString stringWithFormat:@"%@%@",Baseurl,@"/app/inviterule"];
    
    
    [self.navigationController pushViewController:rule animated:YES];
    
    /*
    InviteRuleViewController *rule = [[InviteRuleViewController alloc] init];
    rule.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:rule animated:YES]; */
}

#pragma mark - Delegate
- (void)shareMoreViewDidSelectWithShareType:(ShareType)shareType {
    if (shareType == ShareTypeOther) {
        QRCodeViewController *codeVc = [[QRCodeViewController alloc] init];
        codeVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:codeVc animated:YES];
    }else {
        [self shareDataWithShareType:shareType];
    }
}

- (void)shareDataWithShareType:(ShareType)shareType {
    //构造分享内容
    NSString *url;
    if (AppDelegateInstance.userInfo.spreadLink.length > 0) {
        url = AppDelegateInstance.userInfo.spreadLink;
    }else {
        url = [NSString stringWithFormat:@"%@/app/share",Baseurl];
    }
    
    id<ISSContent> publishContent;
    if (_promoteImg.length > 0) {
        publishContent = [ShareSDK content:[NSString stringWithFormat:@"%@%@",@"随取宝app全新面世!随存随取 8秒注册赢好礼!",url]
                            defaultContent:@""
                                     image:[ShareSDK pngImageWithImage:[UIImage imageNamed:@"app_logo"]]
                                     title:@"随取宝送大礼了！"
                                       url:url
                               description:@""
                                 mediaType:SSPublishContentMediaTypeNews];
    }else {
        publishContent = [ShareSDK content:[NSString stringWithFormat:@"%@%@",@"随取宝app全新面世!随存随取 8秒注册赢好礼!",url]
                            defaultContent:@""
                                     image:[ShareSDK pngImageWithImage:[UIImage imageNamed:@"app_logo"]]
                                     title:@"随取宝送大礼了！"
                                       url:url
                               description:@""
                                 mediaType:SSPublishContentMediaTypeNews];
    }
    
    
    [ShareSDK shareContent:publishContent
                      type:shareType
               authOptions:nil
              shareOptions:nil
             statusBarTips:YES
                    result:^(ShareType type, SSResponseState state,
                             id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                        if (state == SSResponseStateSuccess) {
                            [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"分享成功", nil)];
                            DLOG(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                        }else if (state == SSResponseStateFail) {
                            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"分享失败", nil)];
                            DLOG(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                        }else {
                            DLOG(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                        }
                    }];
}


#pragma mark - Action
- (void)inviteButtonClick {
    _shareView = [[InfoShareView alloc] init];
    _shareView.delegate = self;
    _shareView.shareTitle = @"快来投资理财吧!";
    _shareView.shareContent = [NSString stringWithFormat:@"随取宝APP全新面世!%@",@""];
    _shareView.shareImage = @"";
    _shareView.shareUrl = [NSString stringWithFormat:@"%@/reg?recommendName=%@",Baseurl,AppDelegateInstance.userInfo.userName];
    [_shareView show];
    
}

#pragma mark - Data
- (void)initData {
    
    //[self requestData];
}

- (void)requestData {
    if (AppDelegateInstance.userInfo == nil) {
        [ReLogin goLogin:self];
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"29" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"userId"];
    
    _cacheFileName = [CacheUtil creatCacheFileName:parameters];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

#pragma - HTTPClientDelegate 网络数据回调代理
- (void)startRequest {
    
}

// 返回成功
-(void) httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    [self processData:obj isCache:NO];// 读取当前请求到的数据
}

- (void)processData:(NSDictionary *)dataDics isCache:(BOOL) isCache {
    DLOG(@"dataDics is %@",dataDics);
    if ([[NSString stringWithFormat:@"%@",[dataDics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        if(!isCache){
            // 非缓存数据，且返回的是-1 成功的数据，才更新数据源，否则不保存
            NSString *path =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
            NSString *cachePath = [path stringByAppendingPathComponent:_cacheFileName];// 合成归档保存的完整路径
            [NSKeyedArchiver archiveRootObject:dataDics toFile:cachePath];// 数据归档，存取缓存
        }
        
        if ([dataDics objectForKey:@"promoteImg"] && ![[dataDics objectForKey:@"promoteImg"] isKindOfClass:[NSNull class]]) {
            NSString *promoteImg = [NSString stringWithFormat:@"%@",[dataDics objectForKey:@"promoteImg"]];
            _promoteImg = [CommonClass getImageUrlPath:promoteImg];
        }
        if ([dataDics objectForKey:@"spreadLink"] && ![[dataDics objectForKey:@"spreadLink"] isKindOfClass:[NSNull class]]) {
            _spreadLink = [NSString stringWithFormat:@"%@",[dataDics objectForKey:@"spreadLink"]];
        }
        
        _profitLabel.text = [NSString stringWithFormat:@"%@",[CommonClass formatConversion:[[dataDics objectForKey:@"totalCpsIncome"] doubleValue] type:0]];
        _oneLevelNumLabel.text = [NSString stringWithFormat:@"%@",dataDics[@"cpsCount"]];
        _twoLevelNumLabel.text = [NSString stringWithFormat:@"%@",dataDics[@"cpsNextCount"]];
        
        if (!isCache) {
            // 非缓存数据才显示隐藏
            [self hiddenRefreshView];
        }
        
    }else {
        if (!isCache) {
            // 非缓存数据才显示错误
            [self hiddenRefreshView];
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", [dataDics objectForKey:@"msg"]]];
        }
    }
}

// 返回失败
- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    [self hiddenRefreshView];
    [self readCache];
}

// 无可用的网络
- (void)networkError {
    [self hiddenRefreshView];
    [self readCache];
}

// 加载缓存数据
- (void)readCache {
    // 刷新前先加载缓存数据
    NSString *path =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSString *cachePath = [path stringByAppendingPathComponent:_cacheFileName];// 合成归档保存的完整路径
    NSDictionary *dics = [NSKeyedUnarchiver unarchiveObjectWithFile:cachePath];// 上一次缓存数据
    [self processData:dics isCache:YES];// 读取上一次成功缓存的数据
}

#pragma mark - 刷新
- (void)headerRereshing {
    [self requestData];
}

- (void)footerRereshing {
    [self requestData];
}

- (void)hiddenRefreshView {
    if (!_scrollView.mj_header.hidden) {
        [_scrollView.mj_header endRefreshing];
    }
    if (!_scrollView.mj_footer.hidden) {
        [_scrollView.mj_footer endRefreshing];
    }
}


#pragma mark - View
- (void)initView {
    _scrollView = [UIScrollView scrollViewWithFrame:RECTMAKE(0, 0, MSWIDTH, MSHIGHT - 49 - 64) delegate:self backgroundColor:[UIColor whiteColor] superview:self.view];
    
    _publicImageView = [UIImageView imageViewWithFrame:RECTMAKE(0, 0, MSWIDTH, KAdaptNum(208)) imageFile:@"invite_public" superview:_scrollView];
    
    UIView *profitView = [UIView viewWithFrame:RECTMAKE(0, GetMaxY(_publicImageView), MSWIDTH, KAdaptNum(80)) backgroundColor:nil superview:_scrollView];
    
    UILabel *profitValue = [UILabel labelWithFrame:RECTMAKE(10, KAdaptNum(10), MSWIDTH - 20, KAdaptNum(20)) text:@"累计获得收益(元)" textColor:KGrayColor textFont:13 fitWidth:NO superview:profitView];
    profitValue.textAlignment = NSTextAlignmentCenter;
    
    _profitLabel = [UILabel labelWithFrame:RECTMAKE(10, GetMaxY(profitValue) + KAdaptNum(10), MSWIDTH - 20, KAdaptNum(20)) text:@"0.00" textColor:KColor textFont:20 fitWidth:NO superview:profitView];
    _profitLabel.textAlignment = NSTextAlignmentCenter;
    
    [UIView viewWithFrame:RECTMAKE(0, GetHeight(profitView)-1, MSWIDTH, 1) backgroundColor:KlayerBorder superview:profitView];
    
    UIView *inviteNumView = [UIView viewWithFrame:RECTMAKE(0, GetMaxY(profitView), MSWIDTH, KAdaptNum(80)) backgroundColor:nil superview:_scrollView];
    
    UILabel *oneLevelNumValue = [UILabel labelWithFrame:RECTMAKE(10, KAdaptNum(10), MSWIDTH/2 - 20, KAdaptNum(20)) text:@"一级会员(个)" textColor:KGrayColor textFont:13 fitWidth:NO superview:inviteNumView];
    oneLevelNumValue.textAlignment = NSTextAlignmentCenter;
    
    _oneLevelNumLabel = [UILabel labelWithFrame:RECTMAKE(10, GetMaxY(oneLevelNumValue) + KAdaptNum(10), GetWidth(oneLevelNumValue), KAdaptNum(20)) text:@"0" textColor:KBlackColor textFont:16 fitWidth:NO superview:inviteNumView];
    _oneLevelNumLabel.textAlignment = NSTextAlignmentCenter;
    
    [UIView viewWithFrame:RECTMAKE(MSWIDTH/2, KAdaptNum(20), 1, GetHeight(inviteNumView) - KAdaptNum(40)) backgroundColor:KlayerBorder superview:inviteNumView];
    
    UILabel *twoLevelNumValue = [UILabel labelWithFrame:RECTMAKE(MSWIDTH/2 + 10, KAdaptNum(10), MSWIDTH/2 - 20, KAdaptNum(20)) text:@"二级会员(个)" textColor:KGrayColor textFont:13 fitWidth:NO superview:inviteNumView];
    twoLevelNumValue.textAlignment = NSTextAlignmentCenter;
    
    _twoLevelNumLabel = [UILabel labelWithFrame:RECTMAKE(GetMinX(twoLevelNumValue), GetMaxY(twoLevelNumValue) + KAdaptNum(10), GetWidth(twoLevelNumValue), KAdaptNum(20)) text:@"0" textColor:KBlackColor textFont:16 fitWidth:NO superview:inviteNumView];
    _twoLevelNumLabel.textAlignment = NSTextAlignmentCenter;
    
    _inviteButton = [[ClickButton alloc] initWithFrame:RECTMAKE(20, GetMaxY(inviteNumView) + KAdaptNum(20), MSWIDTH - 40, KAdaptNum(44))];
    [_inviteButton setTitle:@"立即邀请好友" forState:UIControlStateNormal];
    [_inviteButton addTarget:self action:@selector(inviteButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:_inviteButton];
    
    _scrollView.contentSize = CGSizeMake(0, GetMaxY(_inviteButton) + 20);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
